package com.example.tvapp.URL_REGULARS;

import android.content.Context;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class URL_RULES
{
    public final static String root= "/storage/emulated/0/";//Environment.getExternalStorageDirectory().getAbsolutePath()
    public final static  String parentDir=root+"A_TV_HUANG_WEI_MIN/";
    public final static String URLS_=parentDir+"URLS.txt";
    public final static String RULES_=parentDir+"RULES.txt";
    public final static String COLLECTS_=parentDir+"COLLECTS.txt";
    public final static String LOG_=parentDir+"LOG.txt";//日志文件

    static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    private final static String separator=" HUANGWEIMIN ";//分隔符
    private static ArrayList<String[]> URLS;
    private static ArrayList<String[]> RULES;
    private static ArrayList<String[]> COLLECTS;


    public static void initDir(Context context) throws IOException
    {
        File f=new File(parentDir);
        if(!f.exists())
        {
            System.out.println("尝试"+f.mkdir());;
        }
        f=new File(URLS_);
        if(!f.exists()){

            copyAssetsFile(context,"URL_RULES/URLS.txt",URLS_);
        }
        else
        {
            //f.delete();
            //copyAssetsFile(context,"URL_RULES/URLS.txt",URLS_);
        }
        f=new File(RULES_);
        if(!f.exists())
        {
            copyAssetsFile(context,"URL_RULES/RULES.txt",RULES_);
        }
        else {
            //f.delete();
            //copyAssetsFile(context,"URL_RULES/RULES.txt",RULES_);
        }
        f=new File(COLLECTS_);
        if(!f.exists())
        {
            copyAssetsFile(context,"URL_RULES/COLLECTS.txt",COLLECTS_);
        }
        f=new File(LOG_);
        if(!f.exists())
        {
            f.createNewFile();
        }

    }
    public static void addLog(String log) throws IOException
    {
        File f=new File(LOG_);
        if(!f.exists())
        {
            f.createNewFile();
        }
        FileWriter fileWriter=new FileWriter(LOG_,true);
        fileWriter.append(simpleDateFormat.format(new Date())+"   "+log+"\n");
        fileWriter.flush();
        fileWriter.close();
    }
    public static ArrayList<String[]> getURLS() throws Exception
    {
        URLS=new ArrayList<>();
       BufferedReader bufferedReader=new BufferedReader(new FileReader(URLS_));
       String url;
       int i=0;
       while ((url=bufferedReader.readLine())!=null&&url!="\n")
       {
           if(!url.equals(""))
           {
               url=url+separator+i;
               String[] info = url.split(separator);
               URLS.add(info);
               i++;
           }
       }
        bufferedReader.close();
        return  URLS;
    }
    //不加锁可能会导致读取的内容不完整，那个shouldIntercepted()函数可能同时有多个执行
    synchronized public static ArrayList<String[]> getRULES() throws Exception
    {
        RULES=new ArrayList<>();
        BufferedReader bufferedReader=new BufferedReader(new FileReader(RULES_));
        String url;
        while ((url=bufferedReader.readLine())!=null&& !url.equals("\n"))
        {
            if(!url.equals(""))
            {
                String[] info = url.split(separator);
                RULES.add(info);
            }
        }
        bufferedReader.close();
        return  RULES;
    }
    public static ArrayList<String[]> getCOLLECTS() throws Exception
    {
        COLLECTS=new ArrayList<>();
        BufferedReader bufferedReader=new BufferedReader(new FileReader(COLLECTS_));
        String url;
        int i=0;//看作是编号
        while ((url=bufferedReader.readLine())!=null&& !url.equals("\n"))
        {
            //System.out.println("读取收藏"+url+"OO");
            if(!url.equals(""))
            {
                //System.out.println("添加");
                url=url+separator+i;
                String[] info = url.split(separator);
                COLLECTS.add(info);
                i++;
            }
        }
        bufferedReader.close();
        return  COLLECTS;
    }
    public static void addCOLLECTS(String url,String title,String beizhu) throws Exception
    {
       // System.out.println("添加收藏"+url+title+beizhu);
        FileWriter fileWriter=new FileWriter(COLLECTS_,true);
        fileWriter.append("\n"+url+separator+title+separator+beizhu);
        fileWriter.flush();
        fileWriter.close();
    }
    public static void deleteCOLLECTS(int row) throws Exception
    {
        ArrayList<String[]> cs=getCOLLECTS();
        System.out.println("调用"+row+"da"+cs.size());
        cs.remove(row);
        FileWriter fileWriter=new FileWriter(COLLECTS_,false);
        for(int i=0;i<cs.size();i++)
        {
            String entry=cs.get(i)[0]+separator+cs.get(i)[1]+separator+cs.get(i)[2]+"\n";
            System.out.println(entry);
            fileWriter.append(entry);
        }
        fileWriter.flush();
        fileWriter.close();

    }
    public static void deleteURLS(int row) throws Exception
    {
        ArrayList<String[]> cs=getURLS();
        System.out.println("调用"+row+"da"+cs.size());
        cs.remove(row);
        FileWriter fileWriter=new FileWriter(URLS_,false);
        for(int i=0;i<cs.size();i++)
        {
            String entry=cs.get(i)[0]+"\n";
            System.out.println(entry);
            fileWriter.append(entry);
        }
        fileWriter.flush();
        fileWriter.close();

    }
    public static void addRULES(String rule,String[] info) throws Exception
    {
        FileWriter fileWriter=new FileWriter(RULES_,true);
        String entry="\n"+rule;
        if(info!=null)
        {
            for (String i : info)
                entry=entry+separator+i;
        }
        fileWriter.append(entry);
        fileWriter.flush();
        fileWriter.close();
    }
    public static void addURLS(String url,String[] info) throws Exception
    {
        FileWriter fileWriter=new FileWriter(URLS_,true);
        String entry="\n"+url;
        if(info!=null)
        {
            for (String i : info)
                entry=entry+separator+i;
        }
        fileWriter.append(entry);
        fileWriter.flush();
        fileWriter.close();
    }
    /**
     * 将//获取src/main/assets/目录下的文件的文件复制到手机指定的文件夹中
     * @param context context
     * @param assetFileName 参考值：book/test.zip （src/main/assets/book/test.zip）
     * @param phonePath 参考值：/storage/emulated/0/HUANGWEIMIN/BOOK/test.zip
     *
     * */
    private static void copyAssetsFile(Context context, String assetFileName, String phonePath) {
        try {
            File f=new File(phonePath);
            if(!f.exists())
            {
                InputStream inputStream=context.getAssets().open(assetFileName);
                //  System.out.println("尝试:"+inputStream.available());
                FileOutputStream fileOutputStream=new FileOutputStream(phonePath);
                //这里开始拷贝
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
                fileOutputStream.close();//用完了，记得关闭
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
